package com.linq.cool.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linq.cool.common.constants.CacheConstants;
import com.linq.cool.common.constants.Constants;
import com.linq.cool.common.constants.UserConstants;
import com.linq.cool.common.core.domain.Result;
import com.linq.cool.common.core.utils.JwtUtils;
import com.linq.cool.common.core.utils.StringUtils;
import com.linq.cool.common.redis.service.RedisService;
import com.linq.cool.gateway.config.IgnoreWhiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yqlin
 * @Date: 2021/1/18 00:21
 * @Description: 网关鉴权
 * @Version: 1.0.0
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE;
    /**
     * 排除过滤的 uri 地址，nacos自行添加
     */
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;
    @Resource(name = "stringRedisTemplate")
    private ValueOperations<String, String> sops;
    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // /sys/user/getInfo/admin
        String url = exchange.getRequest().getURI().getPath();
        log.info("AuthFilter:{}", url);
        // 跳过不需要验证的路径 无需认证
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            // 直接放行
            return chain.filter(exchange);
        }
        // 请求头信息
        String token = this.getToken(exchange.getRequest());
        log.info("AuthFilter--token:{}", token);
        if (StringUtils.isBlank(token)) {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        String userStr = sops.get(getTokenKey(token));
        log.info("AuthFilter--userStr:{}", userStr);
        if (StringUtils.isNull(userStr)) {
            return setUnauthorizedResponse(exchange, "登录状态已过期");
        }
        JSONObject jsonObject = JSONObject.parseObject(userStr);
        Long userId = Long.valueOf(jsonObject.getString("userId"));
        // token类型
        Integer loginType = Integer.valueOf(jsonObject.getString("loginType"));
        log.info("AuthFilter--loginType类型:{}", loginType);
        if (!JwtUtils.verify(token, userId)) {
            return setUnauthorizedResponse(exchange, "令牌验证失败");
        }
        // 设置过期时间
        redisService.expire(getTokenKey(token), EXPIRE_TIME, TimeUnit.MINUTES);
        ServerHttpRequest mutableReq = null;
        // 系统登录用户 和 前台登录用户
        if (UserConstants.StateEnum.LOGIN_TYPE_SYSTEM.getCode().equals(loginType) || UserConstants.StateEnum.LOGIN_TYPE_WEB.getCode().equals(loginType)) {
            String username = jsonObject.getString("username");
            // 设置userId到request里，后续根据userId，获取用户信息
            mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, String.valueOf(userId))
                    .header(CacheConstants.DETAILS_USERNAME, username).build();
        }
        // 微信登录用户
        if (UserConstants.StateEnum.LOGIN_TYPE_WECHAT.getCode().equals(loginType)) {
            String openId = jsonObject.getString("openId");
            // 设置openId到request里，后续根据userId，获取用户信息
            mutableReq = exchange.getRequest().mutate().header(CacheConstants.DETAILS_USER_ID, String.valueOf(userId))
                    .header(CacheConstants.DETAILS_OPEN_ID, openId).build();
        }
        assert mutableReq != null;
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);
    }

    @Override
    public int getOrder() {
        // 过滤器执行顺序，越小越优先执行
        return -200;
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(CacheConstants.HEADER);
        if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg) {
        ServerHttpResponse originalResponse = exchange.getResponse();
        originalResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] response = null;
        response = JSON.toJSONString(Result.fail(HttpStatus.UNAUTHORIZED.value(), msg)).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = originalResponse.bufferFactory().wrap(response);
        return originalResponse.writeWith(Flux.just(buffer));
    }
}
